package com.qf.base.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * @author 30909
 * 1、 RSA生成密钥对  公钥、私钥 *
 * 2、 公钥加密 私钥解密 *
 * 3、 私钥加密 公钥解密
 */
public class RSAUtil {
    /**
     * 私钥
     */
    public static String privateKeyString;
    /**
     * 公钥
     */
    public static String publicKeyString;

    /**
     * 随机生成密钥对
     */
    public static void genKeyPair() {
        try {

            //拿到RSA的生成器
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            //初始化密钥生成器，初始化大小为1024  默认是512
            keyPairGenerator.initialize(1024, new SecureRandom());
            //生成一个密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            //获取私钥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            //获取公钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            //以base64的形式存储公钥和私钥
            privateKeyString = new String(Base64.encodeBase64(privateKey.getEncoded()));
            publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 公钥加密
     */
    public static String encryptPub(String str, String publicKey) {
        //把公钥base64还原为字节数组
        try {
            byte[] bytes = Base64.decodeBase64(publicKey);
//           公钥又字节数组还原为对象
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                    .generatePublic(new X509EncodedKeySpec(bytes));
            //用于加密对象
            Cipher cipher = Cipher.getInstance("RSA");
            //指定密钥
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            //做加密这件事
            String result = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 私钥解密
     */
    public static String decryptPri(String str, String privateKey) {

        try {
            //还原密钥
            byte[] keyByte = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                    .generatePrivate(new PKCS8EncodedKeySpec(keyByte));
            //数据还原成字节数组             字符转化为 getBytes 数组的方法
            byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            String result = new String(cipher.doFinal(inputByte));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 私钥加密
     */
    public static String encryptPri(String str, String privateKey) {
        try {
            //还原私钥
            byte[] keyByte = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                    .generatePrivate(new PKCS8EncodedKeySpec(keyByte));
            //加密对象
            Cipher cipher = Cipher.getInstance("RSA");
            //指定密钥
            cipher.init(Cipher.ENCRYPT_MODE, priKey);
            //进行加密
            String result = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 公钥解密
     */
    public static String decryptPub(String str, String publicKey) {
        try {
            //把公钥转换为字节数组


            byte[] bytes = Base64.decodeBase64(publicKey);
            //把公钥还原为字对象
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                    .generatePublic(new X509EncodedKeySpec(bytes));
            //密文还原为字节数组
            byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));

            //RSA解密对象
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, pubKey);

            //进行解密
            String result = new String(cipher.doFinal(inputByte));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 测试方法
     *
     * @param args
     */
    public static void main(String[] args) {

        genKeyPair();
        System.out.println("公钥为:" + publicKeyString);
        System.out.println("私钥为:" + privateKeyString);
        String info = "我今天吃的牛肉饭";


        //公钥进行加密 私钥解密测试
        String string1 = encryptPub(info, publicKeyString);
        System.out.println("公钥加密之后为 = " + string1);
        String string2 = decryptPri(string1, privateKeyString);
        System.out.println("私钥进行解密之后为 = " + string2);

        //私钥加密  公钥进行解密测试
        String string4 = encryptPri(info, privateKeyString);
        System.out.println("私钥加密之后为 = " + string4);
        String string5 = decryptPub(string4, publicKeyString);
        System.out.println("string5 = " + string5);

    }
}
